package com.admin_system.service.impl;

import com.admin_system.mapper.UserMapper;
import com.admin_system.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * Spring Security用户详情服务实现
 * 用于Spring Security认证用户
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库查询用户
        User user = null;
        
        // 尝试通过用户名查找
        user = userMapper.findByUsername(username);
        
        // 如果用户名查找失败，尝试通过手机号查找
        if (user == null) {
            user = userMapper.findByPhone(username);
            if (user != null) {
                logger.debug("通过手机号 {} 查找到用户: {}", username, user.getUsername());
            }
        }
        
        if (user == null) {
            logger.error("用户不存在: {}", username);
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        
        // 添加日志，查看用户信息
        logger.info("加载用户: {}，角色: {}", user.getUsername(), user.getRole());
        
        // 确保角色不为空
        String role = user.getRole();
        if (role == null || role.trim().isEmpty()) {
            logger.warn("用户 {} 没有角色，设置默认角色 ROLE_USER", user.getUsername());
            role = "ROLE_USER";
        }
        
        // 创建Spring Security的UserDetails对象
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(), // 使用用户名作为principal
                user.getPassword(),
                user.getIsActive(),
                true, true, true,
                Collections.singletonList(new SimpleGrantedAuthority(role))
        );
    }
} 